#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sys/buffer.h"
#include "sys/IO.h"
#include "sys/shm.h"
#include "sys/ipc.h"

// 定义信号量名称（确保与创建方一致）


int main() {
    // 创建或获取共享内存
    shmid_t shmid = shmget(BUFFER_NAME, sizeof(Buffer));
    if (shmid == NULL) {
        perror("shmget error");
        exit(1);
    }

    Buffer *buffer = (Buffer *)shmat(shmid);
    if (buffer == (void *)-1 || buffer == NULL) {
        perror("shmat error");
        exit(1);
    }

    printf("Initial buffer count: %d\n", buffer->count);

    // 打开命名信号量
    HANDLE semHandle = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, SEM_NAME);
    if (semHandle == NULL) {
        printf("Failed to open semaphore. Error code: %lu\n", GetLastError());
        shmdt(buffer);
        exit(1);
    }

    int cnt = 0;

    while (1) {
        // 等待信号量
        DWORD waitRes = WaitForSingleObject(semHandle, INFINITE);
        if (waitRes != WAIT_OBJECT_0) {
            printf("WaitForSingleObject failed. Error: %lu\n", GetLastError());
            break;
        }

        // 临界区：读取共享内存内容
        while (buffer->count > 0) {
            cnt++;
            printf("%s\n", buffer->strings[buffer->out]);
            buffer->out = (buffer->out + 1) % BUFFER_SIZE;
            buffer->count--;
        }

        // 释放信号量
        if (!ReleaseSemaphore(semHandle, 1, NULL)) {
            printf("ReleaseSemaphore failed. Error: %lu\n", GetLastError());
            break;
        }

        // 退出条件
        if (buffer->count == 0 && buffer->End_or_Not == 0 && cnt > 0) {
            break;
        }

        Sleep(50);  // 加一点休眠，避免空转
    }

    // 清理
    shmdt(buffer);  // 卸载共享内存映射
    CloseHandle(semHandle);  // 关闭信号量句柄

    return 0;
}
